package cn._51doit.flink.day07;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * ProcessFunction可以使用定时器，但是只能针对于KeyedProcessFunction
 * 定时器可以让数据进行增量的聚合或全量的操作（类似于窗口，但是比窗口更灵活）
 *
 * 每个key都可以注册定时器，并且key注册多个定时器（在processElement方法中注册）
 * 定时器触发，会调用onTime方法
 *
 */
public class ProcessFunctionTimerDemo1 {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //spark,1
        DataStreamSource<String> lines = env.socketTextStream("localhost", 8888);

        SingleOutputStreamOperator<Tuple2<String, Integer>> tpStream = lines.map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String value) throws Exception {
                String[] fields = value.split(",");
                return Tuple2.of(fields[0], Integer.parseInt(fields[1]));
            }
        });

        //先keyby再使用定时器
        KeyedStream<Tuple2<String, Integer>, String> keyedStream = tpStream.keyBy(t -> t.f0);

        SingleOutputStreamOperator<Tuple2<String, Integer>> res = keyedStream.process(new KeyedProcessFunction<String, Tuple2<String, Integer>, Tuple2<String, Integer>>() {

            @Override
            public void processElement(Tuple2<String, Integer> value, Context ctx, Collector<Tuple2<String, Integer>> out) throws Exception {
                //不输出数据，注册定时器
                long currentTime = System.currentTimeMillis();
                System.out.println("Register timer : in sumtask :" + getRuntimeContext().getIndexOfThisSubtask() + " at time: " + currentTime);
                ctx.timerService().registerProcessingTimeTimer(currentTime + 20000);

            }

            /**
             * 定时器触发时，会执行onTimer方法
             * @param timestamp
             * @param ctx
             * @param out
             * @throws Exception
             */
            @Override
            public void onTimer(long timestamp, OnTimerContext ctx, Collector<Tuple2<String, Integer>> out) throws Exception {
                System.out.println("onTimer method invoked : in sumtask :" + getRuntimeContext().getIndexOfThisSubtask() + " at time: " + timestamp);
            }
        });

        res.print();

        env.execute();

    }
}
